package com.cangsan.erhai.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cangsan.erhai.config.WechatConfig;
import com.cangsan.erhai.entity.SysUser;
import com.cangsan.erhai.service.SysUserService;
import com.cangsan.erhai.util.StringUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.client.RestTemplate;

import java.util.*;

public class WeChatAuthenticationProvider implements AuthenticationProvider {

    private  WechatConfig wechatConfig;
    private RestTemplate restTemplate;
    private  SysUserService sysUserService;
    public WeChatAuthenticationProvider(WechatConfig wechatConfig, SysUserService sysUserAuthService) {
        this.wechatConfig = wechatConfig;
        this.sysUserService=sysUserAuthService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WechatAuthenticationToken wechatAuthenticationToken = (WechatAuthenticationToken) authentication;
        String loginCode = wechatAuthenticationToken.getPrincipal().toString();
        String phoneCode=wechatAuthenticationToken.getPhoneCode().toString();
        String nickName=wechatAuthenticationToken.getNickName().toString();
        String imageUrl=wechatAuthenticationToken.getImageUrl().toString();
        restTemplate=new RestTemplate();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("appid", wechatConfig.getAppid());
        requestMap.put("secret", wechatConfig.getSecret());
        requestMap.put("code", loginCode);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class,requestMap);
        JSONObject jsonObject= JSONObject.parseObject(responseEntity.getBody());
        String openId=jsonObject.getString("openid");
       SysUser sysUser= sysUserService.getByOpenId(openId);
       if(Objects.isNull(sysUser)){
            SysUser wxUser = new SysUser();
           wxUser.setOpenId(openId);
           wxUser.setAvatar(imageUrl);
        //   wxUser.setPhonenumber(getWxPhone(phoneCode));
           wxUser.setNickName(nickName);
           wxUser.setPassword("123456");
           wxUser.setStatus("0");
           sysUserService.save(wxUser);
           return getauthenticationToken(wxUser,null);
       }else {
           return getauthenticationToken(sysUser,null);
       }

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }
    private String getWxPhone(String phoneCod){
        //获取手机号第一步，获取accessToken
        String accessTokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
        Map<String, String> accessTokenRequestMap = new HashMap<>();
        accessTokenRequestMap.put("appid", wechatConfig.getAppid());
        accessTokenRequestMap.put("secret", wechatConfig.getSecret());
        ResponseEntity<String>  accessTokenResponseEntity = restTemplate.getForEntity(accessTokenUrl, String.class,accessTokenRequestMap);
        JSONObject  accessTokenJsonObject= JSONObject.parseObject(accessTokenResponseEntity.getBody());
        String  accessToken=accessTokenJsonObject.getString("access_token");

        //获取手机号第二部，远程请求获取手机号
        String pohoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken+"";
        JSONObject phoneJson=new JSONObject();
        phoneJson.put("code",phoneCod);

        //设置Http Header
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置返回媒体数据类型
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(phoneJson.toString(), headers);

        String resPhoneStr= restTemplate.postForObject(pohoneUrl, formEntity, String.class);


        JSONObject resPhonJson= JSON.parseObject(resPhoneStr);
        JSONObject phoneInfo=resPhonJson.getJSONObject("phone_info");
        String mobile=phoneInfo.getString("phoneNumber");
            return mobile;
    }


    public WechatAuthenticationToken getauthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities){
        WechatAuthenticationToken authenticationToken=new WechatAuthenticationToken(principal,authorities);
        LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("principal", authenticationToken.getPrincipal());
        authenticationToken.setDetails(linkedHashMap);
        return authenticationToken;
    }

}
